<template>
  <BasicModal
    :width="540"
    :minHeight="260"
    v-bind="$attrs"
    @register="register"
    :title="title"
    @ok="onSave"
    okText="确认选择"
    :showOkBtn="true"
    :showCancelBtn="true"
    :canFullscreen="false"
    :maskClosable="false"
    :centered="true"
    :destroyOnClose="true"
  >
    <div class="panel">
      <div class="item">
        <div class="label"><span class="required">*</span>选择星期</div>
        <div class="fill week">
          <div
            :class="[
              existWeek.has(o.value) ? '' : 'use',
              'cell',
              existWeek.has(o.value) ? 'exist' : weekSelected.has(o.value) ? 'active' : 'tacit',
            ]"
            v-for="o in weekList"
            :key="o.value"
            @click="existWeek.has(o.value) ? null : onWeekItem(o)"
            >{{ o.label }}
          </div>
        </div>
      </div>

      <div class="item">
        <div class="label"><span class="required">*</span>选择时间</div>
        <div class="fill">
          <a-flex gap="small" align="center">
            <a-time-picker
              v-model:value="startTime"
              class="time"
              :minuteStep="30"
              format="HH:mm"
              valueFormat="HH:mm"
              placeholder="开始时间"
            />
            <div class="sep"></div>
            <a-time-picker
              v-model:value="endTime"
              class="time"
              :minuteStep="30"
              format="HH:mm"
              valueFormat="HH:mm"
              placeholder="结束时间"
            />
          </a-flex>
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script>
  import { defineComponent, reactive, ref, toRefs } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { weekList } from '@/api/ds.js';
  import { deleteOperatingPeriod, getExistWeek, saveOperatingPeriod } from './util';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'WeekDialog',
    components: {
      BasicModal,
    },
    emits: ['complete'],
    setup(props, { emit }) {
      const state = reactive({
        behavior: '',
        title: '',
        weekList,
        weekSelected: new Set(),
        startTime: null,
        endTime: null,
        existWeek: new Set(),
      });

      const recordRef = ref({}),
        operatingPeriodDSRef = ref([]);
      const [register, { closeModal }] = useModalInner(
        ({ behavior, operatingPeriodDS, record }) => {
          state.title = '选择营业时间';
          state.behavior = behavior;

          record ||= {};
          recordRef.value = record;
          operatingPeriodDSRef.value = operatingPeriodDS;

          const { startTime = null, endTime = null, incWeek } = record;
          state.startTime = startTime;
          state.endTime = endTime;

          state.weekSelected = new Set(incWeek?.map((o) => o.value) ?? []);
          state.existWeek = getExistWeek(operatingPeriodDS, startTime, endTime);
        },
      );

      function onSave() {
        const { weekSelected, startTime, endTime } = state;
        if (weekSelected.size < 1) {
          return createMessage.error('请选择星期');
        }

        if (!startTime) {
          return createMessage.error('请选择开始时间');
        }

        if (!endTime) {
          return createMessage.error('请选择结束时间');
        }

        if (+startTime.replace(':', '') >= +endTime.replace(':', '')) {
          return createMessage.error('开始时间不能大等于结束时间');
        }

        deleteOperatingPeriod(
          operatingPeriodDSRef.value,
          recordRef.value.startTime,
          recordRef.value.endTime,
        );

        const incWeek = Array.from(weekSelected).map((value) =>
          weekList.find((z) => z.value === value),
        );
        saveOperatingPeriod(operatingPeriodDSRef.value, startTime, endTime, incWeek);

        emit('complete', operatingPeriodDSRef.value);
        closeModal();
      }

      function onWeekItem({ value }) {
        const { weekSelected } = state;

        if (weekSelected.has(value)) {
          weekSelected.delete(value);
        } else {
          weekSelected.add(value);
        }
      }

      return {
        ...toRefs(state),
        register,
        onSave,
        onWeekItem,
      };
    },
  });
</script>
<style lang="less" scoped>
  .panel {
    padding: 8px 16px;

    .item {
      display: flex;
      flex-direction: row;
      padding: 12px 0;

      .label {
        padding-right: 12px;
        color: #091f3d;
        font-size: 13px;
        font-weight: 400;
      }

      .time {
        flex: 1;
      }

      .sep {
        display: inline-block;
        width: 12px;
        height: 2px;
        margin: 0 2px;
        background-color: #ced5df;
      }
    }
  }

  .week {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    cursor: pointer;
    gap: 8px 12px;

    .cell {
      padding: 4px 20px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
    }

    .tacit {
      border: 1px solid #e0e5ec;
      color: #091f3d;
    }

    .active {
      border: 1px solid @primary-color;
      background-color: @primary-color;
      color: #fff;
    }

    .exist {
      background: #e0e5ec;
    }
  }
</style>
